package com.sky.service.impl.admin;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.mapper.admin.DishFlavorsMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorsMapper dishFlavorsMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result<PageResult> getDishByPage(DishPageQueryDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        List<DishVO> dishList = dishMapper.getDishByPage(dto);

        PageInfo<DishVO> pageInfo = new PageInfo<>(dishList);

        PageResult result = new PageResult(pageInfo.getTotal(), pageInfo.getList());

        return Result.success(result);
    }

    @Override
    public Result<Object> addDish(DishDTO dto) {
        // 拷贝dto数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);

        if (dish.getStatus() == null) dish.setStatus(StatusConstant.DISABLE);

        // 添加菜品
        if (dishMapper.insert(dish) == 0) throw new BaseException("增加菜品数据失败");

        // 添加菜品口味
        List<DishFlavor> list = dto.getFlavors();
        if (list != null && !list.isEmpty()) {
            list.forEach(e -> e.setDishId(dish.getId()));
            dishFlavorsMapper.addFlavors(list);
        }

        return Result.success();
    }

    @Override
    public Result<List<Dish>> getDishListByCategoryId(Long categoryId) {
        log.info("getDishListByCategoryId：{}", categoryId);

        List<Dish> dishList = dishFlavorsMapper.getDishListByCategoryId(categoryId);


        return Result.success(dishList);

    }

    @Override
    public Result<Object> setDishStatusById(Long status, Long id) {
        // 直接修改吗? 会不会对别的表造成影响
        // 菜品禁售 关联的套餐要不要下架
        Dish dish = Dish.builder().status(status.intValue()).id(id).build();

        if (dishMapper.updateDish(dish) == 0) throw new BaseException("更改菜品状态失败");

        return Result.success();
    }

    @Override
    public Result<Object> getDishInfoById(Long id) {
        log.info("id为：{}", id);
        DishVO vo = dishMapper.getDishInfoById(id);
        vo.setFlavors(dishFlavorsMapper.getDishFlavorsByDishId(id));

        return Result.success(vo);
    }


    @Override
    public Result<Object> updateDishInfo(DishVO vo) {
        // 拷贝vo参数
        Dish dish = new Dish();
        BeanUtils.copyProperties(vo, dish);


        if (dishMapper.updateDish(dish) == 0) throw new BaseException("修改菜品数据失败");

        return Result.success();

    }

    @Override
    public Result<Object> deleteDishByIds(String ids) {
        // 直接删除吗？ 会不会影响其他表 需不需要操作其他表
        // 删除了菜品，那么菜品口味表中对应的数据还有存在必要吗
        // 如果有套餐关联了该菜品，不能删吧

        //**业务规则：**
        //- 可以一次删除一个菜品，也可以批量删除菜品
        //- 起售中的菜品不能删除
        //- 被套餐关联的菜品不能删除
        //- 删除菜品后，关联的口味数据也需要删除掉

        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());

        // 判断菜品是否启售
        if (dishMapper.isStatus(idList) > 0) return Result.error(MessageConstant.DISH_ON_SALE);

        // 判断要删除的菜品是否关联套餐
        List<SetmealVO> setmealVOList = setmealDishMapper.getSetmealListBydishId(idList);
        if (setmealVOList != null && !setmealVOList.isEmpty())
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

        // 删除该菜品关联的菜品口味数据
        dishFlavorsMapper.deleteDishFlavorsByDishIds(idList);

        // 删除菜品
        if (dishMapper.deleteDishByIds(idList) == 0) return Result.error("未知原因删除菜品失败");

        return Result.success();

    }

    @Override
    @Cacheable(cacheNames = "userDishCache",key = "#categoryId")
    public Result<List<DishVO>> getDishListAllInfoByCategoryId(Long categoryId) {
        // 获取到菜品信息不包括菜品关联口味
        List<DishVO> dishVOList = dishMapper.getDishListAllInfoByCategoryId(categoryId);
        
        // 获取所有菜品关联的菜品口味
        dishVOList.forEach(e -> {
            List<DishFlavor> dishFlavorList = dishFlavorsMapper.getDishFlavorsByDishId(e.getId());
            e.setFlavors(dishFlavorList);
        });

        return Result.success(dishVOList);

    }


}